package sf.database.datasource;

import sf.database.connection.WrapConnection;
import sf.database.dialect.DBDialect;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class WrapDataSource implements DataSource {
    /**
     * 真实的datasource
     */
    private DataSource ds;

    /**
     * 数据库的方言.
     */
    private DBDialect dialect;

    public WrapDataSource(DataSource ds) {
        this.ds = ds;
    }

    public WrapDataSource(DataSource ds, DBDialect dialect) {
        this.ds = ds;
        this.dialect = dialect;
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection conn = ds.getConnection();
        if (conn instanceof WrapConnection) {
            return conn;
        } else {
            return new WrapConnection(conn, dialect);
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        Connection conn = ds.getConnection(username, password);
        if (conn instanceof WrapConnection) {
            return conn;
        } else {
            return new WrapConnection(conn, dialect);
        }
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return ds.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return ds.isWrapperFor(iface);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return ds.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        ds.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        ds.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return ds.getLoginTimeout();
    }


    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return ds.getParentLogger();
    }

    public DataSource getDs() {
        return ds;
    }

    public DBDialect getDialect() {
        return dialect;
    }
}
